<template>
  <div :id="withKeyId" ref="echartRef" class="echart" :style="{ width: width, height: height }"></div>
</template>
<script setup>
const echartRef = ref();
const props = defineProps({
  echartId: {
    type: String,
    require: true,
    default: ''
  },
  width: {
    type: String,
    require: true,
    default: '100%'
  },
  height: {
    type: String,
    require: true,
    default: '100%'
  },
  option: {
    type: Object,
    require: true,
    default: () => {}
  }
});
const withKeyId = computed(() => {
  return props.echartId + 'echart';
});

import elementResizeDetectorMaker from 'element-resize-detector';
import { debounce } from 'lodash';
import useEcharts from './useEcharts.js';

const instance = ref(null);
let setOption = null;

onMounted(() => {
  const { echartsInstance, setOptions, updateSize } = useEcharts(echartRef.value);
  instance.value = echartsInstance;
  setOption = setOptions;
  setOptions(props.option);
  const erd = elementResizeDetectorMaker();
  erd.listenTo(
    document.getElementById(withKeyId.value),
    debounce(() => {
      nextTick(() => {
        //使echarts尺寸重置
        updateSize();
      });
    })
  );
});

//监听配置文件变化
watch(
  () => props.option,
  newValue => {
    setOption && setOption(newValue);
  },
  {
    deep: true
  }
);
</script>
